import pymysql
from dbutils.pooled_db import PooledDB


class DBUtils:
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,
            host="localhost",
            user="root",
            password="123456",
            database="xinyu",
            mincached=2,
            maxcached=5,
            maxshared=3,
            blocking=False,
            maxconnections=10,
        )

    def get_connection(self):
        conn = self.pool.connection()
        cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
        return cur, conn

    def execute_select(self, sql):
        cur, conn = self.get_connection()
        try:
            cur.execute(sql)
            return True, cur.fetchall()
        # except BaseException as e:
        #     return False, None
        finally:
            cur.close()
            conn.close()

    def execute_insert_or_update(self, sql):
        cur, conn = self.get_connection()
        try:
            cur.execute(sql)
            conn.commit()
            row = cur.lastrowid
            return True, row
        except BaseException as e:
            conn.rollback()
            raise (e)
        finally:
            cur.close()
            conn.close()

    def execute_more(self,sqlList):
        cur, conn = self.get_connection()
        try:
            for sql in sqlList:
                cur.execute(sql)
            conn.commit()
            row = cur.lastrowid
            return True, row
        except BaseException as e:
            conn.rollback()
            raise (e)
        finally:
            cur.close()
            conn.close()


DBUtil = DBUtils()
